import json
from sqlalchemy import update,text

from Model.default import SessionLocal
from Model.user.User import time_active_span


def kill_illeagl_time(day,user_id):
    session = SessionLocal()
    try:

        table = 'user_behavior'
        stmt =text(f"UPDATE {table}  SET {day} =  :value  WHERE user_id = :user_id")
        session.execute(stmt,{'value':None,'user_id':user_id})

        session.commit()
    except Exception as e:
        session.rollback()
    finally:
        session.close()


# 根据日期返回当前数据
def get_time_long_data(day,user_id):
    session = SessionLocal()
    try:

        update_stmt= text(f"SELECT {day} FROM user_behavior WHERE user_id = :user_id")
        data=session.execute(update_stmt, {'user_id': user_id}).first()[0]
        session.commit()
        return data
    except Exception as e:
        session.rollback()
    finally:
        session.close()

# 更新在线时长
def updata_time(day,user_id,timestamps,long):
    session = SessionLocal()
    try:
        table='user_behavior'
        update_stmt = text(f"UPDATE {table} SET {day} = :value WHERE user_id = :user_id")
        session.execute(update_stmt, {'value': json.dumps({'logout':timestamps,'long':long}), 'user_id': user_id})
        session.commit()
    except Exception as e:
        session.rollback()
    finally:
         session.close()

# 处理时段次数
def updata_time_span(span, user_id):
    """
    更新指定用户的时间跨度字段。
    :param span: 要更新的列名（如 time_span_1, time_span_2）
    :param user_id: 用户 ID
    """
    # 确保 span 是合法的列名（避免 SQL 注入风险）
    if not span.isidentifier():
        raise ValueError("Invalid column name")

    # 创建会话
    session = SessionLocal()
    try:
        # 使用 SQLAlchemy 的 update 语法更安全
        stmt = (
            update(time_active_span)
            .where(time_active_span.user_id == user_id)
            .values(**{span: getattr(time_active_span, span) + 1})
        )
        session.execute(stmt)
        session.commit()
    except Exception as e:
        session.rollback()
        raise  # 考虑重新抛出异常或处理特定异常
    finally:
        session.close()